#include "uart.h"

#if DEBUG
#include <stdio.h>
#include <stdarg.h>
#endif

void Uart4_Init(uint32_t baud)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	USART_InitTypeDef USART_InitStruct;
	NVIC_InitTypeDef NVIC_InitStruct;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4,ENABLE);
	
	GPIO_InitStruct.GPIO_Mode 	= GPIO_Mode_AF_PP;
	GPIO_InitStruct.GPIO_Pin		= GPIO_Pin_10;
	GPIO_InitStruct.GPIO_Speed	= GPIO_Speed_50MHz;
	GPIO_Init(GPIOC,&GPIO_InitStruct);
	GPIO_InitStruct.GPIO_Mode 	= GPIO_Mode_IN_FLOATING;
	GPIO_InitStruct.GPIO_Pin		= GPIO_Pin_11;
	GPIO_Init(GPIOC,&GPIO_InitStruct);
	
	USART_InitStruct.USART_BaudRate							= baud;
	USART_InitStruct.USART_HardwareFlowControl	= USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode									= USART_Mode_Rx|USART_Mode_Tx;
	USART_InitStruct.USART_Parity								= USART_Parity_No;
	USART_InitStruct.USART_StopBits							= USART_StopBits_1;
	USART_InitStruct.USART_WordLength						= USART_WordLength_8b;
	
	USART_Init(UART4,&USART_InitStruct);
	
	
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority	= 2;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority				= 2;
	NVIC_InitStruct.NVIC_IRQChannel										= UART4_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelCmd								= ENABLE;
	NVIC_Init(&NVIC_InitStruct);
	
	USART_ITConfig(UART4,USART_IT_RXNE,ENABLE);
	USART_Cmd(UART4,ENABLE);
	USART_ClearITPendingBit(UART4,USART_IT_RXNE);
}

void SendByte(uint8_t byte)
{
	
	USART_SendData(UART4,(uint8_t)byte);
	while(USART_GetFlagStatus(UART4,USART_FLAG_TC) == RESET);
}
volatile uint8_t command = 0;
void UART4_IRQHandler(void)
{
	uint8_t data;
	if(USART_GetITStatus(UART4,USART_IT_RXNE) != RESET)
	{
		data = USART_ReceiveData(UART4);
		command = data;
		USART_SendData(UART4,(uint8_t)data);
		USART_ClearITPendingBit(UART4,USART_IT_RXNE);
	}
}
void SendBytes(uint8_t *buf,uint16_t len)
{
	uint16_t i;
	for(i=0;i<len;i++)
	{
		SendByte(buf[i]);
	}
}
#if DEBUG
void mprintf(const char *c,...)
{
	char str[255];
	char *tc = str;
	va_list v;
	va_start(v,c);
	vsprintf(str,c,v);
	while(*tc != '\0')
	{
		SendByte(*tc);
		tc++;
	}
	va_end(v);
}
#endif
